<!--
 * @Descripttion: 本文件是
 * @Author: MZFE_George
 * @Date: 2020-09-14 19:20:00
 * @LastEditors: MZFE_George
 * @LastEditTime: 2020-09-15 16:04:32
-->
<template>
  <span>
    <input
      class="input-file input-file1"
      type="file"
      ref="refFile"
      @change="exportData"
    />
    <input
      class="input-file input-file2"
      type="file"
      ref="upload"
      accept=".xls, .xlsx"
      @change="readExcel"
    />
    <div class="buttons">
      <button @click="btnClick(1)">解析CSV</button>
      <button @click="btnClick(2)">解析EXCEL</button>
      <button @click="calcu">计算</button>
    </div>
  </span>
</template>

<script>
import XLSX from "xlsx";
import Papa from "papaparse";
import _ from "underscore";
const resolveFloat = {
  //除法
  accDiv: (arg1, arg2) => {
    var t1 = 0,
      t2 = 0,
      r1,
      r2;
    try {
      t1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      console.log(e);
    }
    try {
      t2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      console.log(e);
    }
    r1 = Number(arg1.toString().replace(".", ""));
    r2 = Number(arg2.toString().replace(".", ""));
    return this.accMul(r1 / r2, Math.pow(10, t2 - t1));
  },
  //乘法
  accMul: (arg1, arg2) => {
    //console.log(">>>",arg1, arg2)
    var m = 0,
      s1 = arg1.toString(),
      s2 = arg2.toString();
    try {
      if (s1.split(".")[1]) {
        m += s1.split(".")[1].length;
      }
    } catch (e) {
      console.log(e);
    }
    try {
      if (s2.split(".")[1]) {
        m += s2.split(".")[1].length;
      }
    } catch (e) {
      console.log(e);
    }
    return (
      (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
      Math.pow(10, m)
    );
  },
  //加法
  accAdd: (arg1, arg2) => {
    var r1, r2, m;
    try {
      r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
  },
  //减法
  Subtr: (arg1, arg2) => {
    var r1, r2, m, n;
    try {
      r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    n = r1 >= r2 ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
  }
};
export default {
  name: "inputExcel",
  data() {
    return {
      sourceList: [],
      outputs: [],
      mainList: []
    };
  },
  computed: {
    sourceList1() {
      return _.groupBy(this.sourceList, "express");
    }
  },
  methods: {
    calcu() {
      if (this.sourceList1.length == 0 || this.outputs.length == 0) {
        return alert("源数据为空");
      }
      var list = [];
      var keys = Object.keys(this.sourceList1);
      for (let i = 0; i < keys.length; i++) {
        let mainItem = { cost: 0, weight: 0, money: 0, express: "" };
        //每单中的SKULIST
        const skulist = this.sourceList1[keys[i]];
        // console.log("skulist",skulist)
        //每单的单号
        mainItem.express = keys[i];
        //开始计算成本
        skulist.forEach(element => {
          const skuDetail = this.outputs.find(item => {
            return item.id == element.id;
          });
          //console.log(skuDetail);
          // if (!skuDetail.cost || !element.money || !skuDetail.weight) {
          //   console.log(skuDetail);
          // }
          let itemcost = resolveFloat.accMul(element.count, skuDetail.cost);
          let itemmoney = resolveFloat.accMul(element.count, element.money);
          let itemweight = resolveFloat.accMul(element.count, skuDetail.weight);
          mainItem.cost = resolveFloat
            .accAdd(mainItem.cost, itemcost)
            .toFixed(3);
          mainItem.weight = resolveFloat.accAdd(mainItem.weight, itemweight);
          mainItem.money = resolveFloat
            .accAdd(mainItem.money, itemmoney)
            .toFixed(3);
        });
        if (mainItem.weight > 500) {
          mainItem.expresscost = 1.9;
        } else {
          mainItem.expresscost = 1.5;
        }
        list.push(mainItem);
      }
      this.$emit("calcu", list);
      function getSum1(total, num) {
        return resolveFloat.accAdd(total, num.money);
      }

      function getSum2(total, num) {
        return resolveFloat.accAdd(total, num.cost);
      }

      function getSum3(total, num) {
        return resolveFloat.accAdd(total, num.expresscost);
      }
      const allIn = list.reduce(getSum1, 0);
      const allCost = list.reduce(getSum2, 0);
      const allExpresscost = list.reduce(getSum3, 0);
      
      this.$emit("calcuall", [
        allIn,
        allCost + allExpresscost,
        allIn - allCost - allExpresscost
      ]);
      //var obj = {};
    },
    readExcel(e) {
      //表格导入
      var that = this;
      const files = e.target.files;
      if (files.length <= 0) {
        //如果没有文件名
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }

      const fileReader = new FileReader();
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary"
          });
          const wsname = workbook.SheetNames[0]; //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
          that.outputs = []; //清空接收数据
          //编辑数据
          for (var i = 0; i < ws.length; i++) {
            var s = ws[i]["重量"];
            s = s.substring(0, s.length - 1);
            var sheetData = {
              id: +ws[i]["编号"],
              cost: +ws[i]["产品综合成本（不含人工）"],
              expresscost: +ws[i]["快递费用"],
              weight: +s
            };
            that.outputs.push(sheetData);
          }
          this.$refs.upload.value = "";
        } catch (e) {
          console.log("123123", e);
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
    btnClick(index) {
      index = `.input-file${index}`;
      document.querySelector(index).click();
    },
    exportData() {
      let selectedFile = null;
      selectedFile = this.$refs.refFile.files[0];
      if (selectedFile === undefined) {
        return;
      }
      var reader = new FileReader();
      reader.readAsDataURL(selectedFile);
      reader.onload = () => {
        // 检查编码
        // let encoding = this.checkEncoding(evt.target.result);
        // 将csv转换成二维数组
        Papa.parse(selectedFile, {
          encoding: "ANSI",
          complete: res => {
            // UTF8 \r\n与\n混用时有可能会出问题
            let data = res.data;
            if (data[data.length - 1] == "") {
              //去除最后的空行
              data.pop();
            }
            for (let i = 1; i < data.length; i++) {
              this.sourceList.push({
                id: +data[i][0],
                title: data[i][1],
                count: +data[i][3],
                money: +data[i][7],
                express: data[i][8]
              });
            }
            //console.log(this.sourceList);
          }
        });
      };
    }
  }
};
</script>

<style scoped>
.input-file {
  display: none;
}
.buttons {
  max-width: 60%;
  margin:20px auto;
  display: flex;
  justify-content: space-around;
}
.buttons button {
  width: 30%;
}
</style>
